import express from 'express';
import db from './../../lib/dbHelper';
let adminRouter = express.Router();
//index页面
adminRouter.get("/index", (request, response, next) => {
    let muenSQL = "SELECT*FROM `sys_menu` WHERE m_status=1 ORDER BY m_orderby ";
    let webSQL = "SELECT*FROM `websiteinfo` ";
    db.query(webSQL, [], function (err, res1) {
        // console.log(res1);
        /*
        [ RowDataPacket {
    w_id: 0,
    w_title: 'node_BMS',
    w_login: null,
    w_keywords: '打不死的后台管理' } ] 
         * 
        */
        db.query(muenSQL, [], function (err, res2) {
            response.render("./admin/index.html", {
                muen: res2,
                webinfo: res1
            });
        })

    })
})

adminRouter.get('/menu', (req, res, next) => {
    //当请求的是menu的时候,渲染菜单页
    res.render('./admin/menu.html', {});
})

//获取菜单的数据
adminRouter.post('/getmenu', (req, res, next) => {
    //查询数据库
    let querySql = "select * from `sys_menu` where  m_status=1 order by m_orderby";

    //执行sql语句 ,从数据库获取数据
    db.query(querySql, [], function (err, result) {
        let obj = {
            "code": 0,
            "msg": "",
            "count": result.length,
            "data": result
        }
        if (!err) {
            //没有错误的时候将json数据返回到页面
            res.json(obj);
            }
    })
})
//删除数据  (做软删除   修改状态)
adminRouter.post('/deleteByMenuId', (req, res, next) => {
    //查询数据库
    let queryMenDelSql = " UPDATE sys_menu SET m_status=0 WHERE m_id=? ";
    //在请求体中有一个前端页面传过来的参数
    //执行sql中结果有一个受影响的行数  
    db.query(queryMenDelSql, [req.body.mId], function (err, result) {
        if (!err && result.affectedRows >= 1) {
            res.json({
                msg: '删除成功',
                status: 1
            })
        } else {
            res.json({
                msg: '删除失败',
                status: -1,
                err: err
            })
        }
    })
})

//编辑  通过id修改内容
adminRouter.post('/updateMenu', (req, res, next) => {
    //准备sql语句
    let updateMeunSql = " UPDATE sys_menu SET m_name=?,m_url=?,m_no=?,m_parent=?,m_icon=?,m_orderby=?, m_status=? WHERE m_id=?";
    let params = [
        req.body.m_name,
        req.body.m_url,
        req.body.m_no,
        req.body.m_parent,
        req.body.m_icon,
        req.body.m_orderby,
        req.body.m_status,
        req.body.m_id
    ];
    db.query(updateMeunSql, params, (err, result) => {
        if (!err && result.affectedRows >= 1) {
            res.json({
                msg: '修改成功',
                "status": 1
            });
        } else {
            res.json({
                msg: '修改失败',
                "status": -1,
                err: err
            })
        }
    })
});





adminRouter.get('/userMsg', (req, res, next) => {
    res.render('./admin/userMag.html', {});
})






module.exports = adminRouter;